using System;
using System.Collections.Generic;

namespace WebCrawler
{
    /// <summary>
    /// All methods are thread safe
    /// </summary>
    public interface IUrlRepository
    {
        bool Contains(string url);
        /// <summary>
        /// Add new url to the set of urls
        /// </summary>
        /// <param name="url"></param>
        /// <returns>true if the repository didn't contain url and it was added to repository</returns>
        bool AddNew(string url);
        void Complete(string url);
        bool IsComplete(string url);
    }
    
    public class UrlRepository : IUrlRepository
    {
        private Dictionary<string, bool> _urls = new Dictionary<string,bool>();

        public bool Contains(string url)
        {
            lock(_urls) return _urls.ContainsKey(url);
        }

        /// <summary>
        /// Add new url to the set
        /// </summary>
        /// <returns>true if there was no such url in the set, false otherwise</returns>
        public bool AddNew(string url)
        {
            lock (_urls)
            {
                var isNew = !_urls.ContainsKey(url);
                if (isNew) _urls.Add(url, false);
                return isNew;
            }
        }

        public void Complete(string url)
        {
            lock(_urls) _urls[url] = true;
        }

        public bool IsComplete(string url)
        {
            lock (_urls)
            {
                bool res = false;
                _urls.TryGetValue(url, out res);
                return res;
            }
        }
    }
}